package com.hdsx.jxcsxm.utile.http;

import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClient {
   //  private static Logger logger = Logger.getLogger(HttpClient.class);
    private static final String CHARTSET_UTF_8="utf-8";
    public static HttpClient getInstance(){
        return new HttpClient();
    }

    private static CloseableHttpClient  CreateHttpclient(boolean bool){
        try {
            if(bool){
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
                return HttpClients.custom().setSSLSocketFactory(sslsf).build();
            }
        }catch(Exception e) {
            // logger.error(e.getMessage());
            return null;
        }
        return HttpClients.createDefault();
    }

    public JSONObject doPostHttp(String url, Map<String, ?> params){
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000).build();
        String str="";
        List<NameValuePair> param=null;
        CloseableHttpClient httpclient=null;
        HttpPost post=null;
        CloseableHttpResponse response=null;
        try {
            httpclient=CreateHttpclient(false);
            post = new HttpPost(url);
            post.setConfig(requestConfig);
            if(params!=null && params.size() > 0){
                param=getParams(params);
                post.setEntity(new UrlEncodedFormEntity(param, CHARTSET_UTF_8));
            }
            response=httpclient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            str=ResponseUtils.getHttpEntityContent(response, CHARTSET_UTF_8);
            return JSONObject.fromObject(str);
        }catch (Exception e) {
            // logger.error(e.getMessage());
            return null;
        }finally{
            try {
                if(response!=null){
                    response.close();
                }
                if(post!=null){
                    post.releaseConnection();
                }
                if(httpclient!=null){
                    httpclient.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

//            logger.info("-----do POST------");
//            logger.info("url:".concat(url));
//            logger.info("response content:".concat(str));
        }
    }

    /**
     * @Description: map格式 参数  转换为List
     */
    private List<NameValuePair> getParams(Map<String, ?> params){

        if(params != null && !params.isEmpty()){
            List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
            for(Map.Entry<String, ?> entry : params.entrySet()){
                pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
            }
            return pairs;
        }else{
            return null;
        }
    }
    public  String getMACAddress()  {
        try{
            InetAddress ia = InetAddress.getLocalHost();
            // 获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
            byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();

            // 下面代码是把mac地址拼装成String
            StringBuffer sb = new StringBuffer();

            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    sb.append("-");
                }
                // mac[i] & 0xFF 是为了把byte转化为正整数
                String s = Integer.toHexString(mac[i] & 0xFF);
                sb.append(s.length() == 1 ? 0 + s : s);
            }

            // 把字符串所有小写字母改为大写成为正规的mac地址并返回
            return sb.toString().toUpperCase().replaceAll("-", "");
        }catch (Exception e){
            // logger.error(e.getMessage());
            return "获取mac失败";
        }

    }
    public  String getIPAddress()  {
        try{
            InetAddress ia = InetAddress.getLocalHost();
            return ia.getHostAddress();
        }catch (Exception e){
            // logger.error(e.getMessage());
            return "获取IP失败";
        }

    }

}
